from flask import Flask, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
from models import db, Room, Booking, Teacher
from forms import BookingForm, LoginForm, ApprovalForm
from datetime import datetime, time, timedelta, date
from sqlalchemy.orm import joinedload


app = Flask(__name__)
app.config['SECRET_KEY'] = '123456'

# # 添加密钥验证
# if not app.config['SECRET_KEY']:
#     raise ValueError("未配置SECRET_KEY，请检查config.py文件")

# 初始化扩展
db.init_app(app)
login_manager = LoginManager(app)
login_manager.login_view = 'teacher_login'

# 初始化数据库
with app.app_context():
    db.create_all()
    # 添加示例数据
    if not Room.query.first():
        rooms = [
            Room(name="306会议室", description="容纳40人", image="306.jpg", capacity=40),
            Room(name="308会议室", description="容纳30人", image="308.jpg", capacity=30),
            Room(name="410会议室", description="容纳35人", image="410.jpg", capacity=35),
            Room(name="421会议室", description="容纳30人", image="421.jpg", capacity=30)
        ]
        db.session.bulk_save_objects(rooms)
    if not Teacher.query.first():
        teacher = Teacher(username="admin", password="admin123")
        db.session.add(teacher)
    db.session.commit()


@login_manager.user_loader
def load_user(user_id):
    return Teacher.query.get(int(user_id))


# 学生界面路由
@app.route('/')
def index():
    rooms = Room.query.all()
    return render_template('student/index.html', rooms=rooms)


@app.route('/book/<int:room_id>', methods=['GET', 'POST'])
def book_room(room_id):
    room = Room.query.get_or_404(room_id)
    form = BookingForm()
    
    # 计算日期限制
    today = datetime.today().strftime('%Y-%m-%d')
    max_date = (datetime.today() + timedelta(days=7)).strftime('%Y-%m-%d')

    if form.validate_on_submit():
        # 组合完整时间
        start_datetime = datetime.combine(form.date.data, form.start_time.data)
        end_datetime = datetime.combine(form.date.data, form.end_time.data)
        current_datetime = datetime.now()

        # 最终时间校验
        if start_datetime < current_datetime:
            flash("预约开始时间不能早于当前时间", "danger")
            return render_template('student/book.html', 
                form=form, 
                room=room,
                min_date=today,
                max_date=max_date
            )

        # 时间范围验证
        if not (time(8,0) <= form.start_time.data <= time(22,0) and
                time(8,0) <= form.end_time.data <= time(22,0)):
            flash("预约时间必须在8:00-22:00之间", "danger")
            return render_template('student/book.html', form=form, room=room)

        # 时间段冲突检查
        conflict = Booking.query.filter(
            Booking.room_id == room_id,
            Booking.date == form.date.data,
            ((Booking.start_time < end_datetime.time()) & 
             (Booking.end_time > start_datetime.time()))
        ).first()
        
        if conflict:
            flash("该时间段已被预约，请选择其他时间", "danger")
            return render_template('student/book.html', form=form, room=room)

        # 创建预约记录
        booking = Booking(
            student_name=form.name.data,
            student_id=form.student_id.data,
            purpose=form.purpose.data,
            date=form.date.data,
            start_time=form.start_time.data,
            end_time=form.end_time.data,
            room_id=room_id,
            status='pending'
        )
        db.session.add(booking)
        db.session.commit()
        return redirect(url_for('query_booking', booking_id=booking.id))

    return render_template('student/book.html',
        form=form,
        room=room,
        min_date=today,
        max_date=max_date
    )


@app.route('/query')
def query_booking():
    booking_id = request.args.get('booking_id')
    student_id = request.args.get('student_id')

    if booking_id:
        booking = Booking.query.get(booking_id)
    elif student_id:
        booking = Booking.query.filter_by(student_id=student_id).first()
    else:
        booking = None
    return render_template('student/query.html', booking=booking)


# 教师审批路由
@app.route('/teacher/login', methods=['GET', 'POST'])
def teacher_login():
    if current_user.is_authenticated:
        return redirect(url_for('teacher_dashboard'))

    form = LoginForm()
    if form.validate_on_submit():
        teacher = Teacher.query.filter_by(username=form.username.data).first()
        if teacher and teacher.check_password(form.password.data):
            login_user(teacher)
            return redirect(url_for('teacher_dashboard'))
        flash('无效的用户名或密码')
    return render_template('teacher/login.html', form=form)


@app.route('/teacher/dashboard')
@login_required
def teacher_dashboard():
    pending = Booking.query.filter_by(status='pending').all()
    return render_template('teacher/dashboard.html', bookings=pending)


# 教师审批路由修正
@app.route('/teacher/approve/<int:booking_id>', methods=['POST'])
@login_required
def approve_booking(booking_id):
    # 获取当前审批操作
    action = request.form.get('action')
    reason = request.form.get('reason', '')

    # 查询预约记录
    booking = Booking.query.get_or_404(booking_id)

    # 处理审批逻辑
    if action == 'approve':
        booking.status = 'approved'
    elif action == 'reject':
        booking.status = 'rejected'
    else:
        flash('无效的操作类型', 'danger')
        return redirect(url_for('teacher_dashboard'))

    # 更新数据库
    booking.reason = reason
    db.session.commit()

    flash(f'成功{"通过" if action == "approve" else "拒绝"}预约 #{booking_id}', 'success')
    return redirect(url_for('teacher_dashboard'))


@app.route('/teacher/logout')
@login_required
def teacher_logout():
    logout_user()
    return redirect(url_for('index'))


@app.route('/room_status')
@login_required
def room_status():
    # 获取所有会议室及其预约信息
    rooms = Room.query.options(
        joinedload(Room.bookings)
    ).order_by(Room.name).all()
    
    # 组织数据结构
    room_status = []
    for room in rooms:
        # 过滤已过期预约
        active_bookings = [
            booking for booking in room.bookings 
            if booking.date >= date.today()
        ]
        room_status.append({
            'room': room,
            'bookings': sorted(active_bookings, key=lambda x: (x.date, x.start_time))
        })
    
    return render_template('teacher/room_status.html', room_status=room_status)



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
